package com.redis.paihangbang.controller;

import com.redis.paihangbang.entity.StudentScore;
import com.redis.paihangbang.service.RankingService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/ranking")
@RequiredArgsConstructor
public class RankingController {

    private final RankingService rankingService;

    @PostMapping("/update")
    public ResponseEntity<Void> updateScore(@RequestBody StudentScore score) {
        rankingService.updateScore(score.getStudentId(), score.getStudentName(), score.getScore());
        return ResponseEntity.ok().build();
    }

    @PostMapping("/upsert")
    public ResponseEntity<Void> upsert(@RequestBody StudentScore score) {
        rankingService.upsertStudent(score.getStudentId(), score.getStudentName(), score.getScore());
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/delete/{studentId}")
    public ResponseEntity<Boolean> delete(@PathVariable String studentId) {
        boolean ok = rankingService.deleteStudent(studentId);
        return ResponseEntity.ok(ok);
    }

    @GetMapping("/all")
    public ResponseEntity<List<StudentScore>> listAll() {
        return ResponseEntity.ok(rankingService.listAll());
    }

    @GetMapping("/top/{topN}")
    public ResponseEntity<List<StudentScore>> getTopRanking(@PathVariable int topN) {
        List<StudentScore> ranking = rankingService.getTopRanking(topN);
        return ResponseEntity.ok(ranking);
    }

    @GetMapping("/rank/{studentId}")
    public ResponseEntity<Long> getStudentRank(@PathVariable String studentId) {
        Long rank = rankingService.getStudentRank(studentId);
        return ResponseEntity.ok(rank);
    }

    @PostMapping("/rebuild")
    public ResponseEntity<Void> rebuildCache() {
        rankingService.rebuildRankingCache();
        return ResponseEntity.ok().build();
    }
}
